<template>
  <div>
    <BHeader>列表</BHeader>
    <div class="content" ref="scroll" @scroll="autoLoad">
      <ul>
        <router-link v-for="(book,index) in books" :key="index" tag="li" :to="{name:'detail',params:{bid:book.bookId}}">
          <!--<img :src="book.bookCover" alt="">-->
          <img v-lazy="book.bookCover" alt="">
          <div>
            <h4>{{book.bookName}}</h4>
            <p>{{book.bookInfo}}</p>
            <p>{{book.bookPrice}}</p>
            <!--@click.stop防止button的click事件向上传递到router-link的详情跳转事件-->
            <div class="btnList">
              <button @click.stop="remove(book.bookId)">删除</button>
              <button @click.stop="buy(book)">买了</button>
            </div>

          </div>
        </router-link>
      </ul>
      <div @click="handLoadMore" class="more">加载更多</div>
    </div>
  </div>
</template>

<script>
  import BHeader from '../base/BHeader';
  import {getBooks,delBook,getPagination} from '../api';
  import * as Types from '../store/mutations-type';

  export default {
    mounted(){
      // throw new Error();
      let scroll = this.$refs.scroll;
      let top = scroll.offsetTop;
      console.log(top);
      let distance = 0;
      let isMoved = false;//点击的购买的时候 会触发move事件导致重新加载数据
        scroll.addEventListener('touchstart',(e)=>{
          //滚动条不在最顶端 或者 当前盒子在顶端的时候
          console.log(scroll.scrollTop + "  "+ scroll.offsetTop + " "+top);
          if(scroll.scrollTop !=0 || scroll.offsetTop != top) {
            console.log("do nothing");
            return;
          }
        let start = e.touches[0].pageY;//手指点击的开始
        console.log("touchstart "+start)

        let moveE = (e)=>{
          isMoved = true;
          let current = e.touches[0].pageY;//手指滑动的距离
          distance = current - start;//拉动的距离, 负数移除事件
          if(distance > 0){
            if(distance <= 50){//控制拉动距离
              scroll.style.top = distance + top + "px";
            }else{
              distance = 50;
              scroll.style.top = top + 50 + "px";
            }

          }else {
            scroll.removeEventListener("touchmove",moveE);
            scroll.removeEventListener("touchend",endE);
          }
          console.log("touchstart "+start)
        }
        let endE = (e)=>{
          if(!isMoved){return;}
          isMoved = false;
          clearInterval(this.interTimer);
          this.interTimer = setInterval(()=>{//缓慢的还原
            distance -= 1;

            if(distance <= 0){
              clearInterval(this.interTimer);
              distance = 0;
              scroll.style.top = 40+"px";
              //addEventListner清除完成后要恢复初始状态
              scroll.removeEventListener("touchmove",moveE);
              scroll.removeEventListener("touchend",endE);
              console.log("开始加载数据...");
              this.books = [];//getData是加载更多的时候会合并数据，下来加载更多 不需要合并
              this.offset = 0;
              this.getData();
              return
            }

            scroll.style.top = top + distance +"px";

          },10)

        }
        scroll.addEventListener('touchmove',moveE,{ passive: true });
        scroll.addEventListener('touchend',endE,{ passive: true });
      },{ passive: true });

    },
    components: {
      BHeader
    },
    watch:{
      $route(){//路径变化 重新获取数据
        // this.getData();
      }
    },
    created() {
      this.getData();
    },
    methods: {
      //添加商品到store
      buy(book){
        this.$store.commit(Types.ADD_CART,book);
      },
      //自动加载
      autoLoad(){
        //鼠标一滑动 触发太多,开一个定时器，下次触发时将上一次的触发器清除
        clearTimeout(this.timer);//防抖动
        this.timer = setTimeout(()=>{
          //    卷曲的高度 可见区域   总高
          let {scrollTop,clientHeight,scrollHeight} = this.$refs.scroll;
          //console.log(1000);
          if(scrollTop + clientHeight +20 > scrollHeight){
            this.getData();
          }
        },50)
      },
      handLoadMore(){
        this.getData();
      },
      async getData() {

        try {
          if(this.hasMore && !this.isLoading){
            //有更多的时候获取数据
            /*console.log(this.hasMore);
            console.log(!this.isLoading);*/

            this.isLoading  = true;//修改加载状态
            let{hasMore,books} = await getPagination(this.offset);
            //累加已加载数据和加载的
            this.books = [...this.books,...books];
            this.hasMore = hasMore;
            this.offset = this.books.length;//维护偏移量 就是总长度

            //加载完毕
            this.isLoading = false;
          }

        } catch (e) {
          alert('出错了');
        }
      },
      async remove(id){
        await delBook(id);
        // this.getData(); 多了一次请求
        this.books = this.books.filter(item=>item.bookId !== id);
      }
    },
    data() {
      return {
        books: [],
        //代表偏移量
        offset: 0,
        //是否有更多
        hasMore: true,
        isLoading: false,
        msg: 'Welcome to Your Vue.js App'
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .content{
    position: fixed;
    top: 40px;
    bottom: 52px;
    overflow: auto
  }
  .content ul{
    padding: 10px 0;
  }
  .content h4{
    font-size: 20px;
    line-height: 25px;
  }
  .content ul li{
    display: flex;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f1f1;
  }
  .content ul li img{
    width: 130px;
    height: 150px;
  }
  .content p{
    color: #2a2a2a;
    line-height: 25px;
  }
  .content button{
    display: block;
    width: 60px;
    height: 25px;
    background: orangered;
    color: #fff;
    border: none;
    border-radius: 15px;
    outline: none;
    color: #2a2a2a;
    line-height: 25px;
  }

  .more{
    margin: 10px auto;
    background: bisque;
    height: 30px;
    line-height: 30px;
    font-size: 20px;
  }

  .btnList{
    display: flex;
    justify-content: space-around;
  }
</style>
